import csv

with open("D:\\KIPRIS\\Citation\\csv\\errorlist.csv", "r") as errorlist:
    reader = csv.reader(errorlist)
    error_list = list(reader)


import requests
import time
import os


#yearlist = [2005, 2006, 2007, 2008, 2009, 2010]
#lastlist = [160921, 166189, 172469, 170632, 163523, 170101]


def downloader(appnumber):
    year = appnumber[2:6]
    url = "http://plus.kipris.or.kr/openapi/rest/CitationService/citationInfoV3?applicationNumber="+ str(appnumber)+"&accessKey=vHYkrSLI1J9sKpwQ/7gcIO7IGdVenwwsR7iKOigsXlQ="
    start = time.time()
    while True:
        try:
            response = requests.get(url)
            break
        except:
            time.sleep(1)
            pass
    end = time.time()
    A = end - start
    if A < 1:
        time.sleep(1 - A)
    data = response.content
    with open('D:\\KIPRIS\\Citation\\'+str(year) + '\\'+ str(appnumber)+'.xml', 'wb') as f:
        f.write(data)
    n = os.path.getsize('D:\\KIPRIS\\Citation\\'+str(year) + '\\'+ str(appnumber)+'.xml')
    size = round(n / 1024.0, 1)
    A = round(A, 3)
    print(str(appnumber)+ ' - ' + str(response.status_code)+ ' - ' +str(A) +'sec - ' +str(size) + 'KB')

for appnumber in error_list[0]:
    downloader(appnumber)